package com.hanhai.material.wxauth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest;
import com.dingtalk.api.request.OapiUserGetbyunionidRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse;
import com.dingtalk.api.response.OapiUserGetbyunionidResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.utils.jwt.JWTUtil;
import com.hanhai.material.utils.redis.RedisUtil;
import com.hanhai.material.wages.entity.FinUserRoster;
import com.hanhai.material.wages.service.FinUserRosterService;
import com.hanhai.material.wages.service.SysUserService;
import com.mybatisflex.core.query.QueryWrapper;

import com.taobao.api.ApiException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import java.util.Date;
import java.util.Map;

import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.hanhai.material.wages.entity.table.FinUserRosterTableDef.FIN_USER_ROSTER;


/**
 * 钉钉扫码登录
 */
@CrossOrigin
@RestController
@Log4j2
public class LoginController {

    @Value("${Ding.appId}")
    private String appId;

    @Value("${Ding.appSecret}")
    private String appSecret;

    @Value("${Ding.getTokenUrl}")
    private String getTokenUrl;

    @Value("${Ding.getUserInfoUrl}")
    private String getUserInfoUrl;

    @Value("${Ding.getUnionIdUrl}")
    private String getUnionIdUrl;

    @Value("${Ding.getUserByUserIdUrl}")
    private String getUserByUserIdUrl;
    @Value("${Ding.callBackUrl}")
    private String callBackurl;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    FinUserRosterService finUserRosterService;

    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    RedisUtil redisUtil;


    @GetMapping(value = "/api/DingLogin")
    public Result<?> DingLogin(@RequestParam("code") String code) throws Exception {
        log.warn("扫码登录页App:"+appId);
        log.warn("Code:"+code);
        OapiSnsGetuserinfoBycodeResponse bycodeResponse = null;
            // 获取access_token，注意正式代码要有异常流处理
            String access_token = getToken();
            // 通过临时授权码获取授权用户的个人信息
            DefaultDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
            OapiSnsGetuserinfoBycodeRequest reqBycodeRequest = new OapiSnsGetuserinfoBycodeRequest();
            // 通过扫描二维码，跳转指定的redirect_uri后，向url中追加的code临时授权码
            reqBycodeRequest.setTmpAuthCode(code);
            bycodeResponse = client2.execute(reqBycodeRequest,appId, appSecret);
            // 根据unionid获取userid
            String unionid = bycodeResponse.getUserInfo().getUnionid();
            DingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
            OapiUserGetbyunionidRequest reqGetbyunionidRequest = new OapiUserGetbyunionidRequest();
            reqGetbyunionidRequest.setUnionid(unionid);
            OapiUserGetbyunionidResponse oapiUserGetbyunionidResponse = clientDingTalkClient.execute(reqGetbyunionidRequest, access_token);
            // 根据userId获取用户信息
            String userid = oapiUserGetbyunionidResponse.getResult().getUserid();
//            DingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient(getUserByUserIdUrl);
//            OapiV2UserGetRequest reqGetRequest = new OapiV2UserGetRequest();
//            reqGetRequest.setUserid(userid);
//            reqGetRequest.setLanguage("zh_CN");
//            OapiV2UserGetResponse rspGetResponse = clientDingTalkClient2.execute(reqGetRequest, access_token);
//            System.out.println(rspGetResponse.getBody());
//            String body = rspGetResponse.getBody();
//            log.error(body);
//            JSONObject jsonObject= JSON.parseObject(body).getJSONObject("result");
//            JSONArray jsonArray =jsonObject.getJSONArray("dept_id_list");
//            Long deptId=jsonArray.getLongValue(0);
//            log.error("部门ID:"+deptId);
//            String deptString=getDeptDetail(access_token,deptId);
//            //根据自己的需求，获取对应的所需要的东西返回给前端
//            Map<String, Object> map =JSONObject.parseObject(JSONObject.parseObject(body).get("result").toString());
//            map.put("dept", JSONObject.parseObject(deptString).get("result"));
//            log.warn(map);
            QueryWrapper queryWrapper=QueryWrapper.create();
            queryWrapper.where(FIN_USER_ROSTER.USER_ID.eq(userid));
            queryWrapper.where(FIN_USER_ROSTER.ARCHIVES_DATE.eq(fromDateToString("yyyy-MM-dd",new Date())));
            queryWrapper.limit(1);
            FinUserRoster finUserRoster=this.finUserRosterService.getOne(queryWrapper);
            if(finUserRoster==null){
                return ResultTool.fail();
            }
            String token = JWTUtil.sign(finUserRoster.getJobNo(), jwtUtil.getSecret());
//            finUserRoster.setToken(token);
            this.redisUtil.hset(finUserRoster.getJobNo(), "token", token);
            return ResultTool.success(finUserRoster);
    }


    public String getToken() {
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(getTokenUrl);
            OapiGettokenRequest request = new OapiGettokenRequest();
            // 填写步骤一创建应用的Appkey
            request.setAppkey(appId);
            // 填写步骤一创建应用的Appsecret
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            String accessToken = response.getAccessToken();

            return accessToken;
        } catch (ApiException e) {
            throw new RuntimeException();
        }
    }
//    @RequestMapping(value = "/login", method = RequestMethod.GET)
//    public Result<?> login(@RequestParam("code") String authCode) {
//        return ResultTool.success(getGingTalkUser(authCode));
//    }

//    @PostMapping("/api/login")
//    public
    public JSONObject getGingTalkUser(String authCode) {
        JSONObject jsonObject=new JSONObject();


        String accessToken=getAccessToken(appId,appSecret);
        String info=getuserinfo(authCode,accessToken);
        jsonObject.put("GingTalkUser",info);
        jsonObject.put("accessToken",accessToken);

        return jsonObject;
    }
    public static String getAccessToken(String appKey, String appSecret) {

        String getAccessToken="";

        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();

        request.setAppkey(appKey);
        request.setAppsecret(appSecret);
        request.setHttpMethod(HttpMethod.GET.name());

        try {
            OapiGettokenResponse response = client.execute(request);
            if (response.isSuccess()) {
                return response.getAccessToken();
            } else {

            }
        } catch (Exception e) {
            // 需要自己处理异常
            e.printStackTrace();
        }

        return getAccessToken;
    }
    public String getuserinfo(String authCode, String accessToken) {

        String getBody="";

        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(authCode);
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());
            getBody=rsp.getBody();

        } catch (ApiException e) {
            e.printStackTrace();
        }

        return getBody;
    }


    @PostMapping("/api/login")
    public Result Login(){


        return ResultTool.success();
    }
}